package com.ushine.web.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ushine.web.base.mapper.RoleAndPermissionMapper;
import com.ushine.web.base.model.relation.RoleAndFunctionPermissionDO;
import com.ushine.web.base.service.IRoleAndFunPermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: yls
 * @Date: 2021/3/16 17:04
 * @Description: 角色权限关联表操作
 * @Version 1.0
 */
@Service
@Transactional(rollbackFor = {Exception.class})
public class RoleAndFunFunPermissionServiceImpl extends ServiceImpl<RoleAndPermissionMapper, RoleAndFunctionPermissionDO> implements IRoleAndFunPermissionService {

    @Override
    public Boolean insertRoleFunPermission(List<RoleAndFunctionPermissionDO> records) {
        LambdaQueryWrapper<RoleAndFunctionPermissionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleAndFunctionPermissionDO::getRoleId, records.get(0).getRoleId());
        List<RoleAndFunctionPermissionDO> queryRolePermission = list(queryWrapper);
        Map<Long, RoleAndFunctionPermissionDO> rolePermissionMap = new HashMap<>(10);
        // 组装数据
        queryRolePermission.forEach(rolePermissionDO -> rolePermissionMap.put(rolePermissionDO.getFunctionPermissionId(), rolePermissionDO));

        List<RoleAndFunctionPermissionDO> addRolePermissions = new ArrayList<>();
        records.forEach(rolePermissionDO -> {
            if (rolePermissionMap.containsKey(rolePermissionDO.getFunctionPermissionId())) {
                rolePermissionMap.remove(rolePermissionDO.getFunctionPermissionId());
            } else {
                addRolePermissions.add(rolePermissionDO);
            }
        });

        // 保存新增权限
        addRolePermissions.forEach(this::save);
        List<Long> delIds = rolePermissionMap.values().stream().map(RoleAndFunctionPermissionDO::getId).collect(Collectors.toList());
        // 删除多余权限
        removeByIds(delIds);
        return true;
    }
}
